<template>
  <div class="app-container">
    <div class="search-area" v-show="showSearch">
      <el-form
        :model="queryParams"
        @submit.native.prevent
        ref="queryForm"
        size="small"
        :inline="true"
        class="clearfix"
        label-width="auto"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectNumber">
          <el-input
            v-model="queryParams.projectNumber"
            placeholder="请输入项目编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectTypeList">
          <el-select
            v-model="queryParams.projectTypeList"
            multiple
            collapse-tags
            placeholder="请选择项目类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.project_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目级别" prop="projectLevelList">
          <el-select
            v-model="queryParams.projectLevelList"
            multiple
            collapse-tags
            placeholder="请选择项目级别"
            clearable
          >
            <el-option
              v-for="dict in dict.type.project_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value * 1"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目进度" prop="projectProgressList">
          <el-select
            v-model="queryParams.projectProgressList"
            multiple
            collapse-tags
            placeholder="请选择项目进度"
            clearable
          >
            <el-option
              v-for="dict in dict.type.project_progress"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value * 1"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectManager">
          <el-input v-model="queryParams.projectManager" placeholder="请输入项目负责人" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input
            v-model="queryParams.companyName"
            placeholder="请输入公司名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商务负责人" prop="businessManager">
          <el-input v-model="queryParams.businessManager" placeholder="请输入商务负责人" />
        </el-form-item>

        <el-form-item label="项目日期" prop="timeList">
          <el-date-picker
            v-model="queryParams.projectDateList"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>


        <el-form-item label="中标日期" prop="timeList">
          <el-date-picker
            v-model="queryParams.winBiddingDateList"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-content">
      <el-row :gutter="10" class="mb24">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['biz:project:create']"
            >新增</el-button
          >
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:project:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-setting"
            size="mini"
            @click="handleSetType()"
            v-hasPermi="['biz:project:getProjectNumber']"
            >项目编号设置</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button plain size="mini" @click="downloadTemplate()" v-hasPermi="['biz:project:import']"
            >下载导入模板</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-plus" size="mini" @click="importData()" v-hasPermi="['biz:project:import']"
            >导入</el-button
          >
          <input
            type="file"
            @change="onFileChange"
            ref="uploadFileInput"
            enctype="multipart/form-data"
            style="display: none"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          />
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        :data="projectList"
        :default-sort="{ order: 'descending' }"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="项目名称"
          align="center"
          prop="projectName"
          width="240"
          v-if="columns.projectName.visible"
          fixed
        />
        <el-table-column label="项目编号" align="center" prop="projectNumber" v-if="columns.projectNumber.visible"  width="180"  />
        <el-table-column label="项目类型" align="center" v-if="columns.projectType.visible" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.project_type" :value="scope.row.projectType" />
          </template>
        </el-table-column>
        <el-table-column label="公司名称" align="center" prop="companyName" v-if="columns.companyName.visible"   width="180"/>
        <el-table-column
          label="项目级别"
          sortable="custom"
          prop="projectLevel"
          align="center"
          width="140"
          v-if="columns.projectLevel.visible"
        >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.project_level" :value="scope.row.projectLevel" />
          </template>
        </el-table-column>
        <el-table-column
          label="项目金额(元)"
          align="center"
          prop="contractAmount"
          v-if="columns.contractAmount.visible"   width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.contractAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          label="项目负责人"
          align="center"
          prop="projectManager"
          v-if="columns.projectManager.visible"   width="150"
        />
        <el-table-column
          label="项目进度"
          align="center"
          prop="projectProgress"
          v-if="columns.projectProgress.visible"
        />
        <el-table-column
          label="项目日期"
          align="center"
          prop="projectDate"
          sortable="custom"
          v-if="columns.projectDate.visible"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.projectDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="中标时间"
          align="center"
          prop="winBiddingDate"
          sortable="custom"
          v-if="columns.winBiddingDate.visible"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.winBiddingDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="商务负责人"
          align="center"
          prop="businessManager"
          v-if="columns.businessManager.visible"   width="150"
        />
        <!-- <el-table-column label="客户id" align="center" prop="clientId" v-if="columns.clientId.visible" />
                <el-table-column label="合同id" align="center" prop="contractId" v-if="columns.contractId.visible" />
                <el-table-column label="供应商id" align="center" prop="supplierId" v-if="columns.supplierId.visible" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleUpdate(scope.row, true)"
              v-hasPermi="['biz:project:view']"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['biz:project:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['biz:project:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <details-pop :show="open" :disabled="disabled" @cancel="cancel" @refresh="getList" :id="projectId" />
  </div>
</template>

<script>
import { listProject, getProject, delProject, importProject } from '@/api/biz/project'
import { listType } from '@/api/system/dict/type'
export default {
  name: 'Project',
  dicts: ['project_type', 'project_level', 'project_progress'],
  components: { DetailsPop: () => import('@/views/biz/project/ProjectDetails') },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectList: [],
      // 弹出层标题
      title: '',
      // 是否禁止表单填写
      disabled: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectNumber: null,
        projectTypeList: null,
        projectLevelList: null,
        companyName: null,
        projectManager: null,
        businessManager: null,
        projectProgressList: null,
        sortList: [],
        winBiddingDateList: [],
        projectDateList:[]
      },
      // 表单参数
      form: {},
      // 列信息
      columns: {
        projectName: { label: '项目名称', visible: true },
        projectNumber: { label: '项目编号', visible: true },
        projectType: { label: '项目类型', visible: true },
        companyName: { label: '公司名称', visible: true },
        projectLevel: { label: '项目级别', visible: true },
        contractAmount: { label: '项目金额', visible: true },
        projectManager: { label: '项目负责人', visible: true },
        projectProgress: { label: '项目进度', visible: true },
        projectDate: { label: '项目日期', visible: true },
        winBiddingDate: { label: '中标时间', visible: true },
        businessManager: { label: '商务负责人', visible: true },
        // clientId: { label: '客户id', visible: true },
        // contractId: { label: '合同id', visible: true },
        // supplierId: { label: '供应商id', visible: true },
      },
      projectId: null,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    sortChange({ order ,prop}) {
      const type = {
        projectLevel: {
          ascending: 'project_level ASC',
          descending: 'project_level DESC',
        },
        winBiddingDate: {
          ascending: 'win_bidding_date ASC',
          descending: 'win_bidding_date DESC',
        },
      }
      this.$set(this.queryParams, 'sortList', type[prop]&&type[prop][order] ? [type[prop][order]] : [])
      this.$nextTick(() => {
        this.getList()
      })
    },
    /** 查询项目信息列表 */
    getList() {
      this.loading = true
      listProject(this.queryParams).then((response) => {
        this.projectList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.disabled = false
      this.projectId = null
      this.open = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.sortList = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row, readOnly = false) {
      const id = row.id
      this.disabled = readOnly
      this.projectId = id
      this.open = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除项目信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delProject(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'biz/project/export',
        {
          ...this.queryParams,
        },
        `project_${new Date().getTime()}.xlsx`
      )
    },
    handleSetType() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      let url = window.location.origin
      listType({ dictType: 'project_number' }).then((response) => {
        const [item = {}] = response.rows
        loading.close()
        if (item.dictId) {
          window.open(`${url}/system/dict-data/index/${item.dictId}`)
        } else {
          this.$message.error('请先设置字典：project_number')
        }
      })
    },
    onFileChange() {
      const formData = new FormData()
      formData.append('file', this.$refs.uploadFileInput.files[0])
      this.loading = true
      importProject(formData)
        .then((response) => {
          this.loading = false
          this.$modal.msgSuccess('导入成功')
          // 清除文件内容，避免下次不生效
          this.$refs.uploadFileInput.value = ''
          this.resetQuery()
        })
        .catch((err) => {
          this.loading = false
          // 清除文件内容，避免下次不生效
          this.$refs.uploadFileInput.value = ''
        })
    },
    importData() {
      this.$refs.uploadFileInput.click()
    },
    downloadTemplate() {
      this.loading = true
      // 使用相对路径
      const fileUrl = '/projectTemplate.xlsx'
      // 创建一个隐藏的a标签
      const link = document.createElement('a')
      link.href = fileUrl
      link.download = '项目模板.xlsx' // 设置下载文件名
      // 将a标签添加到DOM并触发点击事件
      document.body.appendChild(link)
      link.click()
      // 移除a标签
      document.body.removeChild(link)
      this.loading = false
      this.$modal.msgSuccess('下载成功')
    },
  },
}
</script>
<style scoped lang="scss">
.el-date-editor,
.el-select {
  width: 100%;
}
</style>
